﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CRL.Core.Log
{
    public class LogWriter
    {
        public virtual bool AsyncWrite => true;
        public virtual void Write(IEnumerable<LogItem> logs)
        {
            var first = logs.First();
            var path = Request.RequestHelper.GetFilePath("log/");

            var fileName = $"{DateTime.Now.ToString("yyyy-MM-dd")}";
            if (!string.IsNullOrEmpty(first.TypeName))
            {
                fileName += $".{first.TypeName}";
            }
            fileName += $".txt";
            if (!string.IsNullOrEmpty(first.Folder))
            {
                path = Path.Combine(path, first.Folder);
            }
            Directory.CreateDirectory(path);
            var filePath = Path.Combine(path, fileName);
            var lines = logs.Select(b => b.ToString()).ToList();
            lines.Add("");
            File.AppendAllLines(filePath, lines);
        }
    }
    public class ConsoleLogWriter : LogWriter
    {
        public override bool AsyncWrite => false;
        public override void Write(IEnumerable<LogItem> logs)
        {
            foreach (var log in logs)
            {
                Console.WriteLine($"{log.Time.ToString("yy-MM-dd HH:mm:ss fffff")} {(string.IsNullOrEmpty(log.TypeName) ? "" : "[" + log.TypeName + "]")} {log.Detail}");
            }
        }
    }
}
